<template>
  <div>
    <div style="padding: 0 3px; margin-bottom: 50px;" id="table-wrap">
      <!-- 表格本体 -->
      <crud-form
	      :field-list="fieldList"
	      :showColumnSetting="true"
	      tableOptionWidth="180"
	      :api="cx"
	      :queryParam="formInline"
	      ref="crudForm"
	    >
	      <template slot="searchBar">
	      	<el-form :inline="true" :model="form">
		      <el-form-item size="mini" label="厂家名称">
		        <el-input v-model.trim="formInline.factName" placeholder="请输入厂家名称" class="cjmc" />
		      </el-form-item>
		
		      <el-form-item size="mini" label="分类">
		        <el-select
		          v-model="formInline.kind"
		          class="cjmc"
		          placeholder="请选择"
		          @change="getDevTypeDict2"
		          clearable
		        >
		          <el-option
		            v-for="item in kindDict"
		            :key="item.value"
		            :label="item.name"
		            :value="item.value"
		          ></el-option>
		        </el-select>
		      </el-form-item>
		
		      <el-form-item size="mini" label="类型">
		        <el-select v-model="formInline.factType" class="cjmc" placeholder="请先选择分类" clearable>
		          <el-option
		            v-for="item in kindDict2"
		            :key="item.value"
		            :label="item.name"
		            :value="item.value"
		          />
		        </el-select>
		      </el-form-item>
		
		      <el-form-item size="mini" label="联系人">
		        <el-input v-model="formInline.atten" placeholder="请输入联系人" class="cjmc" clearable />
		      </el-form-item>
		
		      <el-form-item size="mini" label="联系电话">
		        <el-input v-model="formInline.tel" placeholder="请输入联系电话" class="cjmc" maxlength="11" clearable />
		      </el-form-item>
		
		      <el-form-item>
		        <el-button class="newButtonColor SearchBTN" size="mini" @click="queryBtnClick">查询</el-button>
		        <el-button size="mini" class="otherBTN SearchBTN" @click="clearForm">清空</el-button>
		      </el-form-item>
		    </el-form>
	      </template>
	
	      <template slot="tableTopOptionLeft">
	        <erji ref="erji" />
	      </template>
	
	      <template slot="tableOption" slot-scope="{ index, row }">
	        <el-button @click="openDetailWin(index, row)" class="common-btn">详情</el-button>
            <el-button @click="openModifyWin(index, row)" class="common-btn">修改</el-button>
            <el-button @click="Delete(index, row)" class="delete-btn">删除</el-button>
	      </template>
	    </crud-form>
    </div>

    <!-- 二级 -->
    <div>
      <!-- 详情 -->
      <el-dialog
        title="厂家详情"
        :visible.sync="detailWin"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        class="yw"
        width="880px"
      >
        <el-form :inline="true" :model="detailForm" label-width="100px" class="demo-form-inline">
          <div class="form-item">
            <div class="form-item-content">
              <el-form-item label="厂家名称:">
                <span>{{detailForm.factName}}</span>
              </el-form-item>
              <el-form-item label="分类:">
                <span>{{detailForm.kindName}}</span>
              </el-form-item>
              <el-form-item label="类型:">
                <span>{{detailForm.factTypeName}}</span>
              </el-form-item>
              <el-form-item label="所属区域:">
                <span>{{regName}}</span>
              </el-form-item>
              <el-form-item label="详细地址:">
                <span>{{detailForm.addr}}</span>
              </el-form-item>
              <el-form-item label="联系人:">
                <span>{{detailForm.atten}}</span>
              </el-form-item>
              <el-form-item label="联系电话:" prop="freq">
                <span>{{detailForm.tel}}</span>
              </el-form-item>
              <el-form-item label="备注:" prop="startDate">
                <span>{{detailForm.remark}}</span>
              </el-form-item>
              <el-form-item label="厂家图片:">
                <el-image
                  v-if="imageUrl_"
                  :src="imageUrl_"
                  style="width: 105px; height: 105px;  border-radius:5px 5px 5px;"
                />
              </el-form-item>
            </div>
          </div>
        </el-form>
      </el-dialog>
    </div>

    <div>
      <!-- 修改 -->
      <el-dialog
        title="修改厂家"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        :visible.sync="modifyWin"
        width="800px"
        class="yw"
      >
        <el-form ref="form" :model="form" :rules="rules" label-width="80px" size="small" class="qw">
                   <el-row>
            <el-col :span="12">

          <el-form-item label="厂家名称" prop="factName">
            <el-input v-model="form.factName" class="kz" clearable />
          </el-form-item>
                      </el-col>
            <el-col :span="12">

          <el-form-item label="分类" prop="factType">
            <el-select
              v-model="form.kind"
              placeholder="请选择分类"
              class="kz"
              clearable
              @change="getDevTypeDict"
            >
              <el-option
                v-for="item in kindDict"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">

          <el-form-item label="类型" prop="factType">
            <el-select v-model="form.factType" placeholder="请选择类型" class="kz" clearable>
              <el-option
                v-for="item in typeDict"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
            </el-col>
            <el-col :span="12">
          <el-form-item label="所属区域"  prop="regId">
            <el-cascader
              v-model="form.regId"
              class="kz"
              :options="areas"
              :props="props"
              size="mini"
              clearable
              @change="handleChange"
            ></el-cascader>
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
          <el-form-item label="详细地址" prop="addr">
            <el-input v-model.trim="form.addr" class="kz" placeholder="请输入详细地址">
              <el-button
                slot="append"
                style="width: 20%"
                @click="openMapsWin"
                icon="el-icon-map-location"
              />
            </el-input>
          </el-form-item>
            </el-col>
            <el-col :span="12">
          <el-form-item label="联系人" prop="atten">
            <el-input v-model="form.atten" class="kz" clearable />
          </el-form-item>
            </el-col>
          </el-row>

          <el-row>
            <el-col :span="12">
          <el-form-item label="联系电话" prop="tel">
            <el-input v-model="form.tel" class="kz" maxlength="11" clearable />
          </el-form-item>
                      </el-col>
            <el-col :span="12">

          <el-form-item label="图片选择" prop="picId">
            <el-select size="mini" class="kz" clearable @change="chooseImage" v-model="checkValue">
              <el-option
                v-for="item in picUploadType"
                :key="item.value"
                :label="item.name"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
                      </el-col>
          </el-row>

          <el-form-item>
            <el-image
              class="kz"
              :src="imageUrl_"
              style="width: 105px; height: 105px;  border-radius:5px 5px 5px;"
              placeholder="暂无图片"
            ></el-image>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input type="textarea" v-model="form.remark" class="xzcs2" clearable />
          </el-form-item>
        </el-form>

        <div class="dialog-footer">
          <el-button class="editorBTN btnSpace bouncedHold" size="small" @click="addBiaoge()">确定</el-button>
          <el-button size="small" @click="cancleWin('form')" class="editorBTN cancelBTN">取消</el-button>
        </div>
      </el-dialog>
    </div>
    <div>
      <el-dialog
        title="图片本地上传"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        top="30vh"
        @close="imgClose_loca"
        :modal="true"
        :visible.sync="uploadWin"
        width="880px"
        class="dialogClass"
      >
        <singleimageupload ref="singleimageupload" />
      </el-dialog>
    </div>
    <div>
      <el-dialog
        title="图片列表"
        :modal-append-to-body="false"
        :close-on-click-modal="false"
        @close="imgClose"
        top="20vh"
        :modal="true"
        :visible.sync="imagesWin"
        width="880px"
        class="dialogClass"
      >
        <picTable ref="picTable" />
      </el-dialog>
    </div>
    <div>
      <mapseldialog @map-confirm="handleMapConfirm" ref="mapseldialog" />
    </div>
  </div>
</template>

<style lang="scss" scoped>
.aa.cell {
  font-weight: bold;
}
// 二级
.qw {
  width: 1000px;
  height: 100%;
  display: flex;
  flex-wrap: wrap;
  padding-left: 25px;
}
.bz {
  width: 175px;
}

.dw {
  margin-right: 125px;
  display: flex;
}

.dw span {
  margin-top: 8px;
  margin-left: 5px;
}

.dw1 {
  padding-right: 4px;
}

.ntd {
  width: 200px;
  margin-right: 50px;
}

.ntx {
  width: 200px;
}

.kz {
  width: 200px;
  margin-right: 120px;
}

.dq {
  width: 90px;
}

.ww {
  margin-right: 42px;
}

.tup {
  width: 105px;
  height: 102px;
}
.xzcs2 {
  width: 600px;
}

// 详情
.xq {
  margin-left: 70px;
}

.h {
  display: flex;
  flex-wrap: wrap;
}

.k {
  width: 300px;
}

.y {
  width: 700px;
  background: #f5f5f5;
}

// 图片
.tp {
  width: 800px;
}
img {
  display: inline-block;
  vertical-align: middle;
}
</style>
<script>
import erji from "./erji.vue";
import crudForm from "@/components/crudForm/index";
import { cx, menuDelete, xiuGai } from "../../../../api/system/production";
import { DICTDATA, getDict } from "../../../../api/dict";
import { findByParentId } from "../../../../api/system/dict";
import {
  packageDataToMap,
  regName,
  getRegNameByCode,
} from "../../../../utils/area";
import singleimageupload from "../../../../components/upload/singleimageupload";
import { fileid } from "../../../../components/upload/picUpload";
import picTable from "../../../../components/pagetable/picTable";
import imgUrl from "../../../../assets/image/from图片.png";
import { getObjectPicPath } from "../../../../api/system/picture";
import mapseldialog from "../../../../components/mapseldialog";

export default {
  components: { singleimageupload, picTable, mapseldialog,crudForm,erji },
  data() {
  	var isMobileNumber= (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'))
        } else {
          const reg = /^(?:0[1-9][0-9]{1,2}-)?[2-8][0-9]{6,7}$/;
          const regs = /^1(?:3[0-9]|4[5-9]|5[0-9]|6[12456]|7[0-8]|8[0-9]|9[0-9])[0-9]{8}$/;
          if (regs.test(value) || reg.test(value) ) {
            callback()
          } else {
            return callback(new Error('请输入正确的手机号或座机号'))
          }
        }
      };
      var isName= (rule, value, callback) => {
        if (!value) {
          return callback(new Error('不能为空'))
        } else {
          const reg = /^[\u4e00-\u9fa5]{2,6}$/;
          if (reg.test(value)) {
            callback()
          } else {
            return callback(new Error('请输入2-6位中文字符'))
          }
        }
      };
  	let regFormat = (row) => {
		let cellValue = row.regId
	      if (cellValue !== "") {
	        return getRegNameByCode(cellValue);
	      } else {
	        return "";
	      }
    };
    return {
    	kindDict2:[],
      formInline: {factType:'',},
      cx,
      fieldList: [
        { name: "厂家名称", value: "factName" },
        { name: "分类", value: "kindName",},
        { name: "类型", value: "factTypeName",},
        { name: "所属区域", value: "regId", formatter: regFormat },
        { name: "详细地址", value: "addr" },
        { name: "联系人", value: "atten" },
        { name: "联系电话", value: "tel" },
      ],
      imageUrl_: imgUrl,
      sscont: {}, //获取搜索值
      detailWin: false,
      modifyWin: false,
      scqd: false,
      detailForm: {
        factName: "",
        factTypeName: "",
        kindName: "",
        regId: "",
        addr: "",
        atten: "",
        tel: "",
        remark: "",
      },
      form: {
        factName: "",
        factType: "",
        kind: "",
        regId: [],
        addr: "",
        atten: "",
        tel: "",
        remark: "",
        picIds: "",
      },
      rules: {
        kind: [{ required: true, message: "分类不能为空", trigger: "blur" }],
        factType: [
          { required: true, message: "类型不能为空", trigger: "blur" },
        ],
        factName: [
          { required: true, message: "厂家名称不能为空", trigger: "blur" },
        ],
        regId: [
          { required: true, message: "所属区域不可为空", trigger: "blur" },
        ],
        addr: [
          { required: true, message: "详细地址不可为空", trigger: "blur" },
        ],
        atten: [{ required: true, message: "联系人不可为空", trigger: "blur" },
        { validator: isName, trigger: "blur" }
        ],
        tel: [{ required: true, message: "联系电话不可为空", trigger: "blur" },
        { validator: isMobileNumber, trigger: "blur" }],
        remark: [{ required: false, message: "请选取图片", trigger: "blur" },
        {max: 50, message: '长度在不可超过50个字符', trigger: 'blur' }],
      },
      tableData: [],
      search: "",
      pageData: {
        total: 0,
        current: 1,
        pageSize: 10,
      },
      SelectionArray: [], //批量删除
      kindDict:[],
      typeDict: [],
      params: {
        value: "",
      },
      areas: JSON.parse(localStorage.getItem('regTree')),
      props: {
      	checkStrictly: true,
        children: "children",
        label: "name",
        value: "id",
      },
      regName: "",
      areaArray: [],
      areaCode: "",
      mapData: {},
      picUploadType: [
        {
          value: 1,
          name: "图片本地上传",
        },
        {
          value: 2,
          name: "图片库选择",
        },
      ],
      checkValue: "",
      checkModel: [],
      uploadWin: false,
      imagesWin: false,
      imageUrl_: imgUrl,
    };
  },
  created(){
  	getDict(DICTDATA.DEV_KIND).then((res) => {
      this.kindDict = res;
    });
  },
  mounted() {
  	
  },
  methods: {
  	imgClose(){
  		this.checkValue = "";
  		if (this.$refs.picTable.imageUrl) {
  			this.imageUrl_ = this.$refs.picTable.imageUrl;
  		}
  	},
  	imgClose_loca(){
  		this.checkValue = "";
  		if (this.$refs.singleimageupload.imageUrl) {
  			this.imageUrl_ = this.$refs.singleimageupload.imageUrl;
  		}
  	},
  	clearForm() {
      this.formInline = {};
      let that = this;
      setTimeout(function(){
				that.$refs.crudForm.getDataInit();
			},100)
    },
    queryBtnClick() {
    	this.$refs.crudForm.listInfo.query.current = 1
    	this.$nextTick(()=>{
    		this.$refs.crudForm.getDataInit();
    	})
    },
    // 删除
    Delete(index, row) {
      const id = row.id;
      this.$confirm("此操作将永久删除该项数据, 是否继续?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        confirmButtonClass: "messagebox-button",
		cancelButtonClass: "messagebox-button"
      })
        .then(() => {
          menuDelete(id)
            .then((res) => {
              this.$message({
                message: res.mesg,
                type: "success",
		        confirmButtonClass: "messagebox-button",
				cancelButtonClass: "messagebox-button"
              });
              this.$refs.crudForm.getDataInit();
            })
            .catch((err) => {
              this.$message({
                message: "失败",
                type: "error",
              });
            });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //地区数据查询，翻译使用
    queryRegTree(id) {
      return new Promise((resolve, reject) => {
        getAreas(id).then((res) => {
          this.areas = this.getTreeData(res.data.children);
          resolve();
        });
      });
    },
    // 递归算法
    getTreeData(data) {
      for (let i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          // children若为空数组，则将children设为undefined
          data[i].children = undefined;
        } else {
          // children若不为空数组，则继续 递归调用 本方法
          this.getTreeData(data[i].children);
        }
      }
      return data;
    },
    // 详情
    openDetailWin(index, row) {
      
      this.detailWin = true;
      this.detailForm = row;
      const code = row.regId;
      packageDataToMap(code);
      this.regName = regName;
      if (row.picIds != null) {
//      const id = row.picIds;
//      getObjectPicPath(id).then((res) => {
//        this.imageUrl_ = res.data;
          this.imageUrl_ = row.picIds;
//      });
      }
      if (row.picIds == null) {
        this.imageUrl_ = imgUrl;
      }
      this.queryRegTree(-1);
      return this.regName;
    },
    // 修改弹框
    openModifyWin(index, row) {
    	this.checkValue = "";
      //获取当前选择的列表数据
      this.modifyWin = true;
      this.form = {
        id: row.id,
        factName: row.factName,
        factType: row.factType,
        kind: row.kind,
        regId: row.regId,
        addr: row.addr,
        atten: row.atten,
        tel: row.tel,
        remark: row.remark,
      };
      // 获取分类下拉框
      getDict(DICTDATA.DEV_KIND).then((res) => {
        this.kindDict = res;
      });
      this.params.value = this.form.kind;
      findByParentId(this.params).then((res) => {
        this.typeDict = res.data;
      });
      if (row.picIds != null || row.picIds != '') {
      	this.imageUrl_ = row.picIds;
//      const id = row.picIds;
//      getObjectPicPath(id).then((res) => {
//      	if (res.code == '000000') {
//      		this.imageUrl_ = res.data;
//      	}else{
//      		this.$message.error("加载图片失败");
//      		this.imageUrl_ = imgUrl;
//      	}
//      }).catch((err) => {
//            this.$message.error("加载图片失败");
//            this.imageUrl_ = imgUrl;
//          });
      }else{
      	this.imageUrl_ = imgUrl;
      }
    },
    // 输入框点击事件
    openMapsWin() {
      this.$refs.mapseldialog.open({
        lng: this.form.longitude,
        lat: this.form.latitude,
      });
    },
    handleMapConfirm(addres) {
      this.form.addr =
        addres.province + addres.city + addres.district + addres.addr;
    },
    /**
     * 根据设备分类，查询设备类型下拉框
     */
    getDevTypeDict() {
      this.params.value = this.form.kind;
      findByParentId(this.params).then((res) => {
        this.typeDict = res.data;
      });
    },
    getDevTypeDict2() {
      this.params.value = this.formInline.kind;
      findByParentId(this.params).then((res) => {
        this.kindDict2 = res.data;
        this.formInline.factType = null;
      });
    },
    // 多级联动选择器选中事件
    handleChange(value) {
      
    },
    // 下拉框点击事件,不同的选择跳不同的页面
    chooseImage() {
      this.fileList = [];
      if (this.checkModel.length !== 0) {
        this.checkModel = [];
      }
      if (this.checkValue === 1) {
        this.uploadWin = true;
      } else {
        this.uploadWin = false;
      }
      if (this.checkValue === 2) {
        this.imagesWin = true;
      } else {
        this.imagesWin = false;
      }
    },
    addBiaoge() {
      // 获取上传图片的id
      if (fileid) {
//      this.form.picIds = fileid;
      }
      // 获取选中的图片id
      if (this.$refs.picTable !== undefined) {
        this.form.picIds = this.$refs.picTable.imageUrl;
      }
      this.$refs['form'].validate((valid) => {
      	
        if (valid) {
        	this.form.regId = this.form.regId[this.form.regId.length - 1];
          // 发送当前列表修改后的数据
          xiuGai({
          	picIds:this.form.picIds,
            id: this.form.id,
            factName: this.form.factName,
            factType: this.form.factType,
            regId: this.form.regId,
            addr: this.form.addr,
            atten: this.form.atten,
            tel: this.form.tel,
            remark: this.form.remark,
          })
            .then((res) => {
            	if(res.code=="000000"){
            		this.$message({
		                message: "修改成功",
		                type: "success",
		              });
		              this.$refs.crudForm.getDataInit();
		              this.modifyWin = false;
            	}else{
            		this.$message.error(res.data);
            	}
            })
            .catch((err) => {
              this.$message.error("修改失败");
            });
        } else {
          
          return false;
        }
      });
    },
    cancleWin(formName) {
      this.$refs[formName].resetFields();
      this.form = {};
      this.modifyWin = false;
    },
  },
};
</script>
<style lang="scss" scoped>
.form-item-content {
  background-color: #fcfcfc;
  border: 1px solid #eee;
  padding: 15px 15px 0;
}

  .xan {
    width: 200px;
    margin-top: 5px;
    margin-right: 30px;
    margin-left: 30px;
  }

.form-item-title {
  font-size: 16px;
  line-height: 30px;
  color: #434343;
  margin-bottom: 5px;

  .line {
    display: inline-block;
    vertical-align: middle;
    width: 4px;
    height: 14px;
    margin-right: 10px;
    // background-color: #24b3ca;
    border-radius: 4px;
  }
}

/deep/ #app {
  font-family: "Microsoft YaHei";
}

/deep/ .has-gutter {
  background: #f0f0f0 !important;
}

/deep/ .el-table th {
  background-color: transparent;
}

/deep/ .el-table tr {
  background-color: transparent;
}
</style>
